const app = getApp().globalData;
//接口封装





//授权操作
function loginMandate(){
  if(wx.getStorageSync("loginSuccess")){
    return true;
  }else{
    return false;
  }
}

//进行跳转前的数据封装num:额外的参数设定,1:获取上次试卷
async function ParmasData(that,options,num){
  let module = wx.getStorageSync('MODULELIST').module;
  let COURSEINFO = wx.getStorageSync('COURSEINFO');
  let USERDATA = wx.getStorageSync('USERDATA');
  let parmasData = {};
  let url="";
  if(module==133){
    //必然从每日一练页面过来，直接封装参数返回
    url="/dayExam/getDayExamPaper";
    parmas={
      sessionid:USERDATA.sessionid,
      uid:USERDATA.uid,
      courseid:COURSEINFO.id,
      paperid:options.paperid,
      type:module
    };
    parmasData={
      url:url,
      parmas:parmas
    };
    return parmasData;
  }
  let unitid="";
  let kpid="";
  if(options.unitid){
    unitid=options.unitid;
  }
  if(options.kpid){
    kpid=options.kpid;
  }
  if(!num){
    num = -1;
  }
  let parmas={
    sessionid:USERDATA.sessionid,
    uid:USERDATA.uid,
    courseid:COURSEINFO.id,
    type:module,
    unitid:unitid,
    from:app.from,
    market:app.market
  }
  //获取新试卷或历史试卷封装参数
  switch(num){
    //获取上一次的试卷信息
    case 1:
      url="/study/getLastPaper";
      parmas.kpid=kpid;
      break;
    //获取历史试卷的试题
    case 2:
      let paper = await that.lastPaperId(that,options);
      url="/study/loadrecordpaper";
      parmas.paperid=paper.paperid;
      break;
    //获取新试卷的试题
    case 3:
      url="/study/loadnewpaper";
      parmas.kpid=kpid;
      break;
  }
    parmasData={
      url:url,
      parmas:parmas
    };
    return parmasData;

}

//获取上次试卷ID
async function lastPaperId(that,options){
  //获取需要的参数,1:获取上次试卷
  let parmasData = await that.ParmasData(that,options,1);
  let url = parmasData.url;
  let parmas = parmasData.parmas;
  let paper="";
  if(url&&parmas){
    paper = await that.sendPostsSync(url,parmas);
  }else{
    throw new Error('----------------请求地址或请求参数出错-----------------');
  }
  return paper;

}

//跳转到做题界面
function pageturn(url,parmas){
  // 页面传参跳转
  wx.navigateTo({
    url: '/group_admin/pages/tiku/tiku?parmas='+
          JSON.stringify(parmas)+
          '&url='+
          url
  });
}

//弹出提示框
function toolTip(that,options){
  wx.showModal({
        title: '温馨提示',
        content: '是否导入最近一次刷题记录？',
        confirmText:'导入',
        confirmColor:'#FECC34',
        success (res) {
          if (res.confirm) {
          //导入上一次刷题记录,并跳转到做题界面
          that.ParmasData(that,options,2)
          .then(
            value=>{
              // 页面跳转
              that.pageturn(value.url,value.parmas);
            }
          );
          } else if (res.cancel) {
            //导入新的刷题记录,并跳转到做题界面
            that.ParmasData(that,options,3)
            .then(
              value=>{
                // 页面跳转
                that.pageturn(value.url,value.parmas);
              }
            );
          }
        }
      });
}

//判断是否需要弹出提示框，1:非固定内页，2:有做题历史
async function judgeModel(that,options){
  let module = wx.getStorageSync('MODULELIST').module;
  let paper = await that.lastPaperId(that,options);
  if(paper.paperid!='0'&&module!=133){
    let a = 1;
    return true;
  }
  let b = 2;
  return false;
}

//是否启动授权和导入试卷操作
async function clickItem(options){
  let that = this;
  //登陆授权操作
  let res = that.loginMandate();
  if(res){
    //登陆授权成功，判断是否需要弹出提示框，1:非固定内页，2:有做题历史
    res = await that.judgeModel(that,options);
    if(res){
      //弹出提示框，并执行取消和导入操作
      that.toolTip(that,options);
    }else{
      //无做题历史直接跳转新试卷，或者是固定页面直接跳转指定界面
      that.ParmasData(that,options,3)
      .then(
        value=>{
          // 页面跳转
          that.pageturn(value.url,value.parmas);
        }
      );
    }
  }else{
    //登陆授权,弹出提示框
    return false;
  }
}





//获取设备宽高并转化为rpx
function getAdviceInfo(){
  try {
    const res = wx.getSystemInfoSync();
    let baseRpx = 750/res.windowWidth;
    let width = baseRpx*res.windowWidth;
    let height =baseRpx*res.windowHeight;
    let windowInfo={
      width:width,
      height:height
    };
    return windowInfo;
  }catch (e){
    console.log('设备初始化失败',e);
    return null;
  }
}

//获取课程ID
function getCourseId(cb){
  var value = wx.getStorageSync('COURSEINFO');
  if(value.courseId){
    cb(value);
  }else{
    cb(false)
  }
}

//POST请求服务器接口方法  params为json对象  url为接口地址 cb为回调函数 
function sendPosts(url,params,cb){
   //从开发者服务器获取用户信息
   var that = this;
   var newUrl = 'https://ytkapi.cnbkw.com'+url;
  //  var newUrl = 'http://test.ytkapi.cnbkw.com:8091'+url;
  //  console.log("发起请求");
   wx.showLoading({
    title: '加载中',
  })
    wx.request({
      url: newUrl,
      data: params,
      success: function(res) {
        //请求成功
        if (res.statusCode === 200) {
          wx.hideLoading();
          //返回服务器响应数据
          cb(res.data);
          // console.log("请求路径和数据 ");
          // console.log(url);
          // console.log(params);
          // console.log("返回数据");
          // console.log(res.data);
          // console.log("");          
        }else{
          wx.hideLoading();
          cb(false);
        }
        wx.hideLoading()
      }
    })
}

//asycn/await + promise ,解决回调地狱问题
async function sendPostsSync(url,parmas){
  return new Promise((resolve,reject)=>{
    let newUrl = 'https://ytkapi.cnbkw.com'+url;
    // let newUrl = 'http://test.ytkapi.cnbkw.com:8091'+url;
    wx.showLoading({
      title: '加载中',
    })
    //调用请求
    wx.request({
      url:newUrl,
      data:parmas,
      success:(res=>{
        wx.hideLoading();
        console.log("请求路径：",newUrl);
        console.log("请求参数：",parmas);
        console.log("请求结果：",res.data);
        resolve(res.data);
      }),
      fail:(error=>{
        wx.hideLoading();
        console.log("请求失败",error);
        reject(error.data);
      })
    });
  });

}


//微信登陆
function weChatLogin(that,cb){
    //请求微信code
    wx.login({
      success: function(res) {
        if (res.code) {
          //获取用户信息
          wx.getUserInfo({
            success: function(resUserInfo) {
              var params = {
                code: res.code,
                encryptedData: resUserInfo.encryptedData,
                iv: resUserInfo.iv,
                nickname: resUserInfo.userInfo.nickName,
                headimage: resUserInfo.userInfo.avatarUrl,
                type:"0"
              };
              //我的页面的数据需求(用户基本信息)
              var userInfo = resUserInfo.userInfo;
              wx.setStorageSync('USERINFO',userInfo);
              //从开发者服务器获取用户信息
              var url = '/mini-program/WXProgramlogin';
              sendPosts(url,params,function(res){
                if(res){
                  //请求成功
                  wx.setStorageSync('USERDATA',res);
                  console.log("请求成功");
                  cb(true);
                }else{
                  console.log("请求失败");
                  cb(false);
                }
              });
            }
          })
         
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  }

module.exports.weChatLogin = weChatLogin; //微信登陆
module.exports.sendPosts = sendPosts; //亿题库请求用
module.exports.sendPostsSync = sendPostsSync; //亿题库请求用
module.exports.getCourseId = getCourseId; //获取课程ID
module.exports.getAdviceInfo = getAdviceInfo; //获取设备信息

module.exports.clickItem = clickItem; //单击事件：是否启动授权和导入试卷操作
module.exports.loginMandate = loginMandate; //是否已经登陆授权
module.exports.judgeModel = judgeModel; //判断是否需要弹出提示框，1:非固定内页，2:有做题历史
module.exports.lastPaperId = lastPaperId; //获取上次试卷ID
module.exports.ParmasData = ParmasData; //进行跳转前的数据封装
module.exports.toolTip = toolTip; //弹出提示框
module.exports.pageturn = pageturn; //跳转到指定界面（做题界面）